package com.andy.network.entity

import com.andy.network.util.HttpListener
import java.io.Serializable

/**
 * @creator:LuoFan
 * @date:2022/9/28
 * @description:
 */
open class ApiResponse<T>(
    var content: T? = null,
    var errorCode: Int = 0,
    var errorMsg: String = "",
    var error: Throwable? = null
) : Serializable {

    val isSuccess: Boolean
        get() = errorCode == 0

    override fun toString(): String {
        return "ApiResponse(content=$content, errorCode=$errorCode, errorMsg=$errorMsg, error=$error)"
    }
}

data class ApiSuccessResponse<T>(val response: T) : ApiResponse<T>(content = response)

data class ApiErrorResponse<T>(val code: Int, val msg: String) : ApiResponse<T>(errorCode = code, errorMsg = msg)

data class ApiFailedResponse<T>(val throwable: Throwable) : ApiResponse<T>(error = throwable)

fun <T> ApiResponse<T>.parseData(listener: HttpListener<T>) {
    when (this) {
        is ApiSuccessResponse -> listener.onSuccess(this.response)
        is ApiFailedResponse -> listener.onFailed(this.error)
        is ApiErrorResponse -> listener.onError(this.errorCode, this.errorMsg)

    }
}